/*
 * WordPress版同城信息发布
 * author: huangbin
 * 技术支持微信号：wxid_i8yk4fp0uep322
 * 开源协议：MIT
 *  *Copyright (c) 2018 https:/www.tczhb.club All rights reserved.
 */

var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js')

import config from '../../utils/config.js'
var app = getApp();

var pageCount = app.globalData.page_size ? app.globalData.page_size : 5;

Page({
  data: {    
    postsList: [],
    postsShowSwiperList:[],
    isLastPage:false,    
    page: 1,
    search: '',
    categories: 0,
    showerror:"none",
    showCategoryName:"",
    categoryName:"",
    showallDisplay:"block", 
    displayHeader:"none",
    displaySwiper: "none",
    floatDisplay: "none",
    displayfirstSwiper:"none",
    categoriesList: [],
    currentTab: 0,
    topNav: []
  },
  formSubmit: function (e) {
    var url = '../list/list'
    var key ='';
    if (e.currentTarget.id =="search-input")
    {
      key = e.detail.value;
    }
    else{
      key = e.detail.value.input;
    }
    if (key != '') {
      url = url + '?search=' +key;
      wx.navigateTo({
        url: url
      })
    }
    else
    {
      wx.showModal({
        title: '提示',
        content: '请输入内容',
        showCancel: false,
      });
    }
  },
  onShareAppMessage: function () {
    return {
      title: '“' + config.getWebsiteName+'”网站微信小程序,基于WordPress版小程序构建.技术支持：www.watch-life.net',
      path: 'pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onPullDownRefresh: function () {
    var self = this;
    self.setData({
      showerror: "none",
      showallDisplay:"none",
      displaySwiper:"none",
      floatDisplay:"none",
      isLastPage:false,
      page:0,
      postsShowSwiperList:[]
    });
    this.fetchTopFivePosts(); 
    
  },
  onLoad: function (options) {
    var self = this; 
    self.getConfig();
  },
  onShow: function (options){
     wx.setStorageSync('openLinkCount', 0);
  },
  //获取配置信息  
  getConfig: function() {
    var self = this;
    var getConfigRequest = wxRequest.getRequest(Api.getConfig());
    getConfigRequest.then(response => {
      if (response.statusCode == 200 && response.data.code == 200){
        if (response.data.data){
          var res = response.data.data;
          //每页数据个数
          app.globalData.page_size = res.page_size;
          //发布信息上传图片个数
          app.globalData.post_img_num = res.post_img_num;
          //程序名称
          app.globalData.app_name = res.app_name;
          /* 开始加载页面数据 */
          self.fetchTopFivePosts();
          self.fetchCategoriesData();
          /* end */
        }
      }
    })
  },
  //获取幻灯片
  fetchTopFivePosts: function () {
    var self = this;
    //取置顶的文章
    var getPostsRequest = wxRequest.getRequest(Api.getSwiperPosts());
    getPostsRequest.then(response => {
      if (response.statusCode == 200 && response.data.code == 200 && response.data.data.length > 0) {
        self.setData({
          postsShowSwiperList: response.data.data,
          postsShowSwiperList: self.data.postsShowSwiperList.concat(response.data.data.map(function (item) {
              return item;
          })),
          showallDisplay: "block",
          displaySwiper: "block"
        });
      }
      else {
        self.setData({
          displaySwiper: "none",
          displayHeader: "block",
          showallDisplay: "block",
        });
      }
    })
    .then(response=>{
      self.fetchPostsData(self.data);
    })
    .catch(function (response){
      console.log(response); 
      self.setData({
        showerror: "block",
        floatDisplay: "none"
      });
    })
    .finally(function () {
    });            
  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    wx.showLoading({
      title: '正在加载',
      mask: true
    });  
    var self = this;    
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (!data.categories) data.categories = 0;
    if (!data.search) data.search = '';
    data.author_exclude = 1;
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };
    var getPostsRequest = wxRequest.getRequest(Api.getPosts(data));
    getPostsRequest
        .then(response => {
            if (response.statusCode === 200) {
              if (response.data.code === 200){
                if (response.data.data.length < pageCount) {
                    self.setData({
                        isLastPage: true
                    });
                }
                self.setData({
                    floatDisplay: "block",
                    postsList: self.data.postsList.concat(response.data.data.map(function (item) {
                      var strdate = item.published_time
                      item.dateStr = util.getDateDiff(strdate);
                      item.post_content = util.removeHTML(item.post_content);
                      return item;
                    })),
                });
              }
            }
            else {
                if (response.data.code == "rest_post_invalid_page_number") {
                    self.setData({
                        isLastPage: true
                    });
                    wx.showToast({
                        title: '没有更多内容',
                        mask: false,
                        duration: 1500
                    });
                }
                else {
                    wx.showToast({
                        title: response.data.message,
                        duration: 1500
                    })
                }
            }
        })
        .catch(function (response)
        {
            if (data.page == 1) {

                self.setData({
                    showerror: "block",
                    floatDisplay: "none"
                });

            }
            else {
                wx.showModal({
                    title: '加载失败',
                    content: '加载数据失败,请重试.',
                    showCancel: false,
                });
                self.setData({
                    page: data.page - 1
                });
            }

        })
        .finally(function (response) {
            wx.hideLoading();
            wx.stopPullDownRefresh();
        });
  },
  //获取分类列表
  fetchCategoriesData: function () {
    var self = this;
    //调用API从本地缓存中获取分类列表
    var categoryListArr = wx.getStorageSync('categoryList') || [];
    if (categoryListArr.length > 0){
      self.setData({
        floatDisplay: "block",
        categoriesList: categoryListArr
      });
    }else{
      var getCategoriesRequest = wxRequest.getRequest(Api.getCategories(true));
      getCategoriesRequest.then(response => {
        if (response.statusCode === 200) {
          if(response.data.code === 200){
            self.setData({
              floatDisplay: "block",
              categoriesList: self.data.categoriesList.concat(response.data.data.map(function (item) {
                return item;
              })),
            });
            wx.setStorageSync('categoryList', self.data.categoriesList);
          }
        }
        else {
          console.log(response);
        }
      })
      .catch(function (response) {
        console.log(response);
      }).finally(function () {
      })
    }
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage)
    {
      self.setData({
        page: self.data.page + 1
      });
      this.fetchPostsData(self.data);
    }
  },
  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    wx.navigateTo({
      url: url
    })
  },
  //首页图标跳转
  onNavRedirect:function(e){      
      var redicttype = e.currentTarget.dataset.redicttype;
      var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
      var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
      var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData;
      if (redicttype == 'apppage') {//跳转到小程序内部页面         
          wx.navigateTo({
              url: url
          })
      }
      else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
      {
          url = '../webpage/webpage?url=' + url;
          wx.navigateTo({
              url: url
          })
      }
      else if (redicttype == 'miniapp')//跳转到其他app
      {
          wx.navigateToMiniProgram({
              appId: appid,
              envVersion: 'release',
              path: url,
              extraData: extraData,
              success(res) {
                  // 打开成功
              },
              fail: function (res) {
                  console.log(res);
              }
          })
      }
      
  },
  //跳转至某分类下的信息列表
  redictIndex: function (e) {
    //console.log('查看某类别下的文章');  
    var id = e.currentTarget.dataset.id;
    var url = '../list/list?categoryID=' + id;
    wx.navigateTo({
      url: url
    });
  },
  // 跳转至查看小程序列表页面或文章详情页
  redictAppDetail: function (e) {
      // console.log('查看文章');
      var id = e.currentTarget.id;
      var redicttype = e.currentTarget.dataset.redicttype;
      var url = e.currentTarget.dataset.url == null ? '':e.currentTarget.dataset.url;
      var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
      
      if (redicttype == 'detailpage')//跳转到内容页
      {
          url = '../detail/detail?id=' + id;
          wx.navigateTo({
              url: url
          })
      }
      if (redicttype == 'apppage') {//跳转到小程序内部页面         
          wx.navigateTo({
              url: url
          })
      }
      else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
      {
          url = '../webpage/webpage?url=' + url;
          wx.navigateTo({
              url: url
          })          
      }
      else if (redicttype == 'miniapp')//跳转到其他app
      {
          wx.navigateToMiniProgram({
              appId: appid,
              envVersion: 'release',
              path: url,
              success(res) {
                  // 打开成功
              },
              fail: function (res) {
                  console.log(res);
              }
          })
      }
  },
  //返回首页
  redictHome: function (e) {
    //console.log('查看某类别下的文章');  
    var id = e.currentTarget.dataset.id,
      url = '/pages/index/index';
    wx.switchTab({
      url: url
    });
  },
  //图片预览
  previewImage: function (e) {
    var that = this;
    var imgs = e.currentTarget.dataset.imgs;
    var urls = [];
    for (var i = 0, len = imgs.length; i < len; i++){
      urls.push(imgs[i]['url']);
    }
    wx.previewImage({
      current: e.currentTarget.dataset.img,
      urls: urls
    })
  },
  /**
  * 打开地图标注
  */
  open_map: function (e) {
    //console.log(e.currentTarget.dataset)
    var lat = e.currentTarget.dataset.lat;
    var lon = e.currentTarget.dataset.lon;
    if (lat != '0') {
      wx.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lon),
        scale: 28
      });
    } else {
      wx.showToast({
        image: '../../resource/images/static/error.png',
        title: '座标错误,无法定位!',
      });
    }
  },
  /**
 * 联系他
 */
  tap_phone: function (e) {
    var phone = e.currentTarget.dataset.uphone;
    wx.makePhoneCall({ phoneNumber: phone });
  },
  /**
  * 切换tab栏
  */
  swichTab: function (e) {
    var that = this;
    var current_id = e.currentTarget.dataset.current;
    if (that.data.currentTab === current_id) {
      return false;
    } else {
      that.setData({
        currentTab: current_id
      });
    }
    //最新发布
    if (current_id === "0"){
      that.setData({
        categories: 0
      });
    }
    //猜你喜欢 
    else if (current_id === "1"){
      var logs = wx.getStorageSync('readLogs') || [];
      var cat_id_arr = [];
      if (logs.length > 0) {
        logs.filter(function (log) {
          cat_id_arr.push(log[2])
        });
        if (cat_id_arr.length > 0){
          that.setData({
            categories: cat_id_arr.join(',')
          });
        }
      }
    }
    that.setData({
      isLastPage: false,
      page: 1
    });
    this.fetchPostsData(that.data);
  },
  onReachBottom:function(){
    var self = this;
    this.loadMore();
  },
  //发布
  tapPublish:function(){
    var url = '../topic/topic';
    wx.navigateTo({
      url: url
    }) 
  }
})
